package com.tianji.promotion.listener;


import com.tianji.common.constants.MqConstants;
import com.tianji.promotion.entity.dto.UserCouponDTO;
import com.tianji.promotion.service.IUserCouponService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class PromotionListener {

    private final IUserCouponService userCouponService;


    /**
     * 接收优惠券领取的消息
     *
     * @param dto
     */
    @RabbitListener(bindings = @QueueBinding(exchange = @Exchange(value = MqConstants.Exchange.PROMOTION_EXCHANGE, type = ExchangeTypes.TOPIC),
            value = @Queue(value = "coupon.receive.queue", durable = "true"),
            key = MqConstants.Key.COUPON_RECEIVE))
    public void receiveCoupon(UserCouponDTO dto) {
        log.info("收到优惠券领取消息：{}", dto);
        // 校验参数
        if (dto == null || dto.getCouponId() == null || dto.getUserId() == null) {
            log.error("优惠券领取消息参数错误：{}", dto);
            return;
        }
        userCouponService.checkAndCreateUserCouponNew(dto);
    }
}
